package com.flame.application.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flame.application.dao.BookDao;
import com.flame.application.entity.bean.Book;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Jflame
 * @version 1.0.0
 * @since 2025/8/30
 */
@Slf4j
@Service
public class BookService extends ServiceImpl<BookDao, Book> {
    @Resource
    private BookDao bookDao;

    private static final String FILE_DIR = "static/books/";

    public String upload(MultipartFile file) {
        String filePath = saveFile(file);
        if (filePath == null) {
            return null;
        }
        Book book = new Book();
        UUID uuid = UUID.randomUUID();
        book.setBookId(uuid.toString());
        book.setTitle(file.getOriginalFilename());
        book.setPath(filePath);
        int insert = bookDao.insert(book);
        if (insert <= 0) {
            log.error("插入 {} 数据失败", file.getOriginalFilename());
            return null;
        }
        return uuid.toString();
    }

    public String saveFile(MultipartFile file) {
        try {
            String classPath = ResourceUtils.getURL("classpath:").getPath();
            String folderPath = classPath + FILE_DIR;
            File folder = new File(folderPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            String filePath = folder.getAbsolutePath() + "/" + fileName;
            file.transferTo(new File(filePath));
            return filePath;
        } catch (IOException e) {
            log.error("上传文件失败", e);
        }
        return null;
    }

}
